<?php

/**
 * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com
 */

namespace app\mobile\controller;

use app\admin\model\ConsumerClaimLog;
use app\admin\model\IdentityLoginLog;
use app\admin\model\Order;
use app\admin\model\Platform;
use app\admin\model\StoreJoinActivity;
use app\admin\model\template\ClaimConsume;
use app\admin\model\UserToken;
use app\admin\model\WriteLog;
use app\BaseController;
use think\facade\Db;
use app\admin\model\FigureSystem;



/**
 * 用户操作
 *
 * @author Administrator
 *
 */
class User extends BaseController
{



    /**
     * 获取openid
     * mobile/user/getOpenId
     *
     * @param
     *            code
     */
    public function getOpenId()
    {

        $request = $this->request;
        $data['platform_id']=  $request->platform_id;
        $where[] = ['id','=', $request->platform_id];
        $platfrom = new Platform();
        $platfromInfo =  $platfrom ->where($where)->find();
        $code = input('code');
        if (empty($code)) {
            return result(-1, 'code为空');
        }
        $appid = $platfromInfo['xcx_appid'];
        $secret = $platfromInfo['xcx_appsecret'];
        $api = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
        $info = httpGet($api); // get请求网址，获取数据
        $json = json_decode($info); // 对json数据解码
        $arr = get_object_vars($json); // 返回一个数组。获取$json对象中的属性，组成一个数组
        if (!empty($arr['errcode'])) {
            return result(-1, $arr['errmsg']);
        } else {
            $openid = $arr['openid'];
            if (empty($openid)) {
                return result(-1, 'fail');
            } else {
                return result(0, 'success', $arr);
            }
        }
    }

    /**
     * 获取微信授权手机号码
     * mobile/user/getTelphone
     *
     * @param
     *            code
     */
    public function getTelphone()
    {

        $request = $this->request;
        $data['platform_id']=  $request->platform_id;
        $where[] = ['id','=', $request->platform_id];
        $platfrom = new Platform();
        $platfromInfo =  $platfrom ->where($where)->find();

        $code = input('code');
        if (empty($code)) {
            return result(-1, 'code为空');
        }

        $appid = $platfromInfo['xcx_appid'];
        $secret = $platfromInfo['xcx_appsecret'];

        $api = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;

        $info = httpGet($api); // get请求网址，获取数据
        $arr_access_token = json_decode($info, true); // 对json数据解码

        if (!$arr_access_token) {
            return result(-1, '请求异常');
        }

        $access_token = $arr_access_token['access_token'];
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $access_token;
        $send_data = array(
            'code' => $code
        );
        $data = json_encode($send_data);
        $phone = json_decode(wtw_request($url, $data));

        return result(0, 'success', $phone);
    }

    /**
     * 敏感词校验
     *mobile/user/msgSecCheck
     *
     * @param
     *            openid
     * @param
     *            content 内容
     * @param
     *            scene 1 资料；2 评论；3 论坛；4 社交日志
     * @param
     *            nickname 用户昵称
     */
    public function msgSecCheck()
    {
        $system = FigureSystem::where("id", 1)->find();
        if (empty($system)) {
            return result(-1, '平台配置为空');
        }
        $content = input('content');
        if (empty($content)) {
            return result(-1, 'content为空');
        }
        $content = mb_convert_encoding($content, "UTF-8", "auto");
        $appid = $system['appid'];
        $secret = $system['appsecret'];
        $api = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
        $info = httpGet($api); // get请求网址，获取数据
        $arr_access_token = json_decode($info, true); // 对json数据解码
        if (!$arr_access_token) {
            return result(-1, '请求异常');
        }
        $access_token = $arr_access_token['access_token'];
        $url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" . $access_token;
        $send_data = array(
            'content' => $content,
            'version' => 2,
            'scene' => input('scene'),
            'openid' => input('openid')
        );
        if (!empty(input('nickname'))) {
            $send_data['nickname'] = mb_convert_encoding(input('nickname'), "UTF-8", "auto");
        }
        $data = json_encode($send_data);
        $result = json_decode(wtw_request($url, $data));
        return result(0, 'success', $result);
    }

    /**
     * 用户授权
     * /mobile/user/register
     *
     * @param
     *            pid
     * @param
     *            openid
     * @param
     *            unionid
     * @param
     *            avatar 头像
     * @param
     *            nickname 昵称
     * @param
     *            telphone 手机号码
     */
    public function register()
    {
        $request = $this->request;
        $domain = $request->domain();
        $param = $request->param();
        if (isset($param['unionid']) &&$param['unionid']  ) {
            $data['unionid'] = $param['unionid'];
        }
        if (isset($param['openid']) &&$param['openid']  ) {
            $data['openid'] = $param['openid'];
        }
        if (!empty(input('avatar'))) {
            $data['avatar'] = input('avatar');
        } else {
            $data['avatar'] = $domain . "/imgs/def_user.png";
        }
        if (isset($param['nickname']) && $param['nickname']  ) {
            $data['nickname'] =  $param['nickname'];
        } else {
            $data['nickname'] = '用户' . substr( $param['telphone'], -4);
        }


        $data['platform_id']=  $request->platform_id;
        if (!empty($param['telphone'])) {
            $data['telphone'] = $param['telphone'];
            if (!preg_match("/^1[3456789]\d{9}$/", $param['telphone'])) {
                return result(-1, '非法的手机号码');
            }
            if (strlen(input('telphone') )> 11){
                return result(-1, '手机号有误');
            }
        }
        $userModel = new \app\admin\model\User;
        $res = $userModel->where(['telphone' => $param['telphone']])->find();
        if (!$res) {
            if (isset($param['password']) && $param['password']  ) {
                $data['password'] =  md5($param['password']);
            }
            $userModel->save($data);
            $uid = $userModel->id;
        } else {
            if (isset($param['password']) && $param['password']  ) {
                $data['password'] =  md5($param['password']);
                if ( $res['password'] ){
                    if ($res['password'] !=    $data['password'] ){
                        return result(-1, '密码有误');
                    }
                }
            }

            $uid = $res['id'];
//            if (empty($res['qrcode'])) {
//                $url = "pages/index/index";
//                $userUrl = qr_code($uid, $url, 'user');
//                $data['qrcode'] = $userUrl;
//            }

          $res->save($data);
        }
        return result(0, 'success', ['uid' => $uid,'platform_id'=> $request->platform_id]);
    }



    /**
     * 用户信息
     * /mobile/user/userInfo
     *
     * @param
     *            uid
     */
    public function userInfo()
    {
        try {
            $request = $this->request;
            $param = $request->param();
            $userModel = new \app\admin\model\User;
            $user = $userModel->where('id',  $param['uid'])->find();
            if (empty($user)) {
                return result(-1, '未找到用户');
            }
//            if (empty($user['qrcode'])) {
//                $url = "pages/index/index";
//                $userUrl = qr_code( $request->user_id, $url, 'user');
//                $user->save([
//                    'qrcode' => $userUrl
//                ]);
//            }

            $user['is_store'] =  0;
            $storeModel = new \app\admin\model\Store();

            $storeInfo   = $storeModel->where(['uid' => $param['uid']])->order('create_time','desc')->find();

            if ($storeInfo){  // 用户已经开了店铺
                if ($storeInfo['status'] == 0){
                    $user['store_status'] = 1;
                    $user['store_name'] =  $storeInfo['store_name'] ;
                    $user['store_id'] =  $storeInfo['id'];
                }else if ($storeInfo['status'] == 1){
                    $user['store_status'] = 2;
                    $user['store_name'] =  $storeInfo['store_name'] ;
                    $user['store_id'] =  $storeInfo['id'];
                }else if ($storeInfo['status'] == 2){
                    $user['store_status'] = 3;
                    $user['store_name'] =  $storeInfo['store_name'] ;
                    $user['store_id'] =  $storeInfo['id'];
                }

            }else{
                $user['store_status'] = 0;
                $user['store_name'] = '' ;
                $user['store_id'] =  0;
            }

            $ConsumerClaimLog  = new ConsumerClaimLog();
            $platformConsumerTotal = $ConsumerClaimLog->where(['send_way'=> 1,'uid'=> $param['uid']])->where('status','<>',0)->count();
            $platformConsumerUse = $ConsumerClaimLog->where(['status' => 2,'send_way'=> 1,'uid'=> $param['uid']])->count();
            $platformConsumerWaitUse = $ConsumerClaimLog->where(['status' => 1,'send_way'=> 1,'uid'=> $param['uid']])
                ->where('expire_time','>',time())->count();
            $platformConsumerWaitExpired = $ConsumerClaimLog->where(['status' => 1,'send_way'=> 1,'uid'=> $param['uid']])
                ->where('expire_time','<',time())->count();
            $storeConsumerTotal = $ConsumerClaimLog->where(['uid'=> $param['uid']])->where('status','<>',0)->where('send_way','in',[1,2])->count();
            $storeConsumerUse = $ConsumerClaimLog->where(['status' => 2,'uid'=> $param['uid']])->where('send_way','in',[1,2])->count();
            $storeConsumerWaitUse = $ConsumerClaimLog->where(['status' => 1,'uid'=> $param['uid']])->where('send_way','in',[1,2])
                ->where('expire_time','>',time())->count();
            $storeConsumerWaitExpired = $ConsumerClaimLog->where(['status' => 1,'uid'=> $param['uid']])->where('send_way','in',[1,2])
                ->where('expire_time','<',time())->count();

            $couponConsumerTotal = $ConsumerClaimLog->where(['send_way'=> 3,'uid'=> $param['uid']])->count();
            $couponConsumerUse = $ConsumerClaimLog->where(['status' => 2,'send_way'=> 3,'uid'=> $param['uid']])->count();
            $couponConsumerWaitUse = $ConsumerClaimLog->where(['status' => 1,'send_way'=> 3,'uid'=> $param['uid']])
                ->where('expire_time','>',time())->count();
            $couponConsumerWaitExpired = $ConsumerClaimLog->where(['status' => 1,'send_way'=> 3,'uid'=> $param['uid']])
                ->where('expire_time','<',time())->count();



            $ticketConsumerTotal = $ConsumerClaimLog->where(['send_way'=> 4,'uid'=> $param['uid']])->count();
            $ticketConsumerUse = $ConsumerClaimLog->where(['status' => 2,'send_way'=> 4,'uid'=> $param['uid']])->count();
            $ticketConsumerWaitUse = $ConsumerClaimLog->where(['status' => 1,'send_way'=> 4,'uid'=> $param['uid']])
                ->where('expire_time','>',time())->count();
            $ticketConsumerWaitExpired = $ConsumerClaimLog->where(['status' => 1,'send_way'=> 4,'uid'=> $param['uid']])
                ->where('expire_time','<',time())->count();


            $user['platform_consumer_total'] = $platformConsumerTotal;
            $user['platform_consumer_wait_use'] = $platformConsumerWaitUse;
            $user['platform_consumer_use'] = $platformConsumerUse;
            $user['platform_consumer_wait_expired'] = $platformConsumerWaitExpired;


            $user['store_consumer_total'] = $storeConsumerTotal;
            $user['store_consumer_wait_use'] = $storeConsumerWaitUse;
            $user['store_consumer_use'] = $storeConsumerUse;
            $user['store_consumer_wait_expired'] = $storeConsumerWaitExpired;

            $user['coupon_consumer_total'] = $couponConsumerTotal;
            $user['coupon_consumer_wait_use'] = $couponConsumerWaitUse;
            $user['coupon_consumer_use'] = $couponConsumerUse;
            $user['coupon_consumer_wait_expired'] = $couponConsumerWaitExpired;

            $user['ticket_consumer_total'] = $ticketConsumerTotal;
            $user['ticket_consumer_wait_use'] = $ticketConsumerWaitUse;
            $user['ticket_consumer_use'] = $ticketConsumerUse;
            $user['ticket_consumer_wait_expired'] = $ticketConsumerWaitExpired;

            return result(0, '用户信息', $user);
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getMessage());
            exit();
        }
    }


    public function userList(){
        $request = $this->request;
        $param = $request->param();
        $userModel = new \app\admin\model\User;
        $where =[];
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $ConsumerClaimLog  = new ConsumerClaimLog();
        $ConsumerClaimLogList = $ConsumerClaimLog->where(['consumer_id' => $param['consume_id']])->select()->toArray();
        $uidId =[];
        if ($ConsumerClaimLogList){
            $uid = array_column($ConsumerClaimLogList,'uid');
        }

        if (isset( $param['nickname']) &&  $param['nickname']){
            $total = $userModel->where(['platform_id'=> $request->platform_id])
//                ->where(function ( $query) use ($consumerId) {
//                    if ($consumerId){
//                        $query->where(['write_store_id'=>$store_id ]);
//
//                    }
//                })
                ->where('nickname|telphone','like',"%".$param['nickname']."%")->count();
            if ($total) {
                $list = $userModel->where(['platform_id'=> $request->platform_id])
                    ->where('nickname|telphone','like',"%".$param['nickname']."%")->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
            } else {
                $list = array();
            }

        }else{
            $total = $userModel ->where(['platform_id'=> $request->platform_id])->count();
            if ($total) {
                $list = $userModel->where(['platform_id'=> $request->platform_id])->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
            } else {
                $list = array();
            }

        }

        foreach ($list as $key => $value ){
            $orderModel = new WriteLog();
            $pay_amount  = $orderModel->where(['uid' => $value['id']])
              ->sum('pay_amount');
            $list[$key]['total_amount'] = $pay_amount;
        }
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));

    }

    public function userConsumer(){
        $request = $this->request;
        $param = $request->param();
        $userModel = new \app\admin\model\User;
        $user = $userModel->where('telphone',  $param['telphone'])->find();
        if (empty($user)){
            return result(-1, '用户不存在');
        }

        $where[] = ['uid'  ,'=', $user['id']];
        $consumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
        $StoreJoinActivityModel =  new StoreJoinActivity();
        $store_id = 0;
        $activityId =[];
        if ( isset($param['store_id']) &&  $param['store_id']){
            $store_id =  $param['store_id'];
            $StoreJoinActivityList = $StoreJoinActivityModel
                ->where(['store_id' => $param['store_id']])->select()->toArray();
            if ($StoreJoinActivityList){
                $activityId = array_column($StoreJoinActivityList,'activity_id');
            }
        }


        $where[] = ['expire_time'  ,'>=', time()];
        $where[] = ['status'  ,'=', 1];
        $where[] = ['issue_type'  ,'<>', 3];

        $where[] = [' consumer_type'  ,'in', [0,1]];


        $total  = $consumerClaimLogModel
            ->where($where)
            ->where(function ( $query) use ($store_id,$activityId) {
                if ($store_id){
                    $query->where(['store_id'=>$store_id ]);
                    if ($activityId){
                        $query->whereOr('activity_id','in',$activityId);
                    }
                }
            })->count();

        $list =  $consumerClaimLogModel
            ->where($where)
            ->where(function ( $query) use ($store_id,$activityId) {
                if ($store_id){
                    $query->where(['store_id'=>$store_id ]);
                    if ($activityId){
                        $query->whereOr('activity_id','in',$activityId);
                    }
                }

            })
            ->order('expire_time')->select();

        //echo  $consumerClaimLogModel->getLastSql();exit;
        foreach ($list  as $key => $value){
            $consumerModel  =  new \app\admin\model\Consumer();
            $consumerInfo =   $consumerModel->where(['id' => $value['consumer_id']])->find();
            $list[$key]['consumer_info'] = $consumerInfo;

            $list[$key]['expire_time'] = date('Y-m-d ',$value['expire_time']);

        }

        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,

        ));
    }






}